﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;

namespace iControl.Windows
{
	/// <summary>
	/// Interaction logic for SettingsWindow.xaml
	/// </summary>
	public partial class SettingsWindow: Window
	{
		#region Variable Declaration
		private bool _IsShortcutsEditable;
		private bool _Saved;
		#endregion

		#region Constructor
		public SettingsWindow()
		{
			InitializeComponent();

			var xProvider = this.FindResource("KeyMapsDS") as XmlDataProvider;
			xProvider.Source = new Uri(KeyMapManager.KeyMapFileLocation);
		}
		#endregion

		#region Event Handlers
		private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
		{
			btnChangeShortcuts.Content = Properties.Resources.SettingsWindow_EnableShortcutChange;
		}
		private void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if( _IsShortcutsEditable ) //Disable shortcut changes.
				btnChangeShortcuts_Click(null, null);

			if( !_Saved )
			{
				MessageBoxResult result = MessageBox.Show(Properties.Resources.CancelSettingsConfirmation, this.Title,
					MessageBoxButton.YesNo, MessageBoxImage.Question);

				e.Cancel = (result == MessageBoxResult.No);
			}
		}

		private void DragWindow(object sender, MouseButtonEventArgs e)
		{
			DragMove();
		}
		private void btnCloseX_Click(object sender, RoutedEventArgs e)
		{
			this.Close();
		}

		private void KeyboardHook_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if( !this.Dispatcher.CheckAccess() )
			{
				this.Dispatcher.Invoke(new System.Windows.Forms.KeyEventHandler(this.KeyboardHook_KeyDown), sender, e);
				return;
			}

			if( lstKeyMaps.SelectedItems.Count > 0 )
			{
				var item = lstKeyMaps.SelectedItems[0] as XmlElement;
				StringBuilder modifiers = new StringBuilder();

				if( (e.KeyCode & System.Windows.Forms.Keys.LControlKey) == System.Windows.Forms.Keys.LControlKey ||
					(e.KeyCode & System.Windows.Forms.Keys.RControlKey) == System.Windows.Forms.Keys.RControlKey || e.Control )
				{
					modifiers.Append("Control, ");
				}
				if( (e.KeyCode & System.Windows.Forms.Keys.LShiftKey) == System.Windows.Forms.Keys.LShiftKey ||
					(e.KeyCode & System.Windows.Forms.Keys.RShiftKey) == System.Windows.Forms.Keys.RShiftKey || e.Shift )
				{
					modifiers.Append("Shift, ");
				}
				if( (e.KeyCode & System.Windows.Forms.Keys.LMenu) == System.Windows.Forms.Keys.LMenu ||
					(e.KeyCode & System.Windows.Forms.Keys.RMenu) == System.Windows.Forms.Keys.RMenu || e.Alt )
				{
					modifiers.Append("Alt, ");
				}
				if( modifiers.Length == 0 )
					modifiers.Append("  ");

				if( e.KeyCode != System.Windows.Forms.Keys.LControlKey && e.KeyCode != System.Windows.Forms.Keys.RControlKey
					&& e.KeyCode != System.Windows.Forms.Keys.LMenu && e.KeyCode != System.Windows.Forms.Keys.RMenu &&
					e.KeyCode != System.Windows.Forms.Keys.LShiftKey && e.KeyCode != System.Windows.Forms.Keys.RShiftKey )
				{
					item.Attributes[KeyMap.KeyAttributeName].Value = e.KeyCode.ToString();
				}

				item.Attributes[KeyMap.ModifierAttributeName].Value = modifiers.ToString().Remove(modifiers.Length - 2, 2);
			}
		}

		private void btnChangeShortcuts_Click(object sender, RoutedEventArgs e)
		{
			if( _IsShortcutsEditable )
			{
				btnChangeShortcuts.Content = Properties.Resources.SettingsWindow_EnableShortcutChange;
				Controller.DefaultInstance.KeyboardHook.KeyDown -= new System.Windows.Forms.KeyEventHandler(KeyboardHook_KeyDown);
				_IsShortcutsEditable = false;
			}
			else
			{
				btnChangeShortcuts.Content = Properties.Resources.SettingsWindow_DisableShortcutChange;
				Controller.DefaultInstance.KeyboardHook.KeyDown += new System.Windows.Forms.KeyEventHandler(KeyboardHook_KeyDown);
				_IsShortcutsEditable = true;
			}
		}
		private void btnOK_Click(object sender, RoutedEventArgs e)
		{
			bool allDone = true;

			try
			{
				allDone = Settings.DefaultInstance.Save();

				var xProvider = this.FindResource("KeyMapsDS") as XmlDataProvider;
				xProvider.Document.Save(KeyMapManager.KeyMapFileLocation);

				KeyMapManager.DefaultInstance.Reload();
				_Saved = true;

				this.Close();
			}
			catch( Exception ex )
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				System.Diagnostics.Debug.WriteLine(ex.StackTrace);

				allDone = false;
			}

			if( !allDone )
			{
				MessageBox.Show(Properties.Resources.UnableToSaveSettings, this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}
		private void btnCancel_Click(object sender, RoutedEventArgs e)
		{

			this.Close();
		}
		private void btnResoreDefaults_Click(object sender, RoutedEventArgs e)
		{
			MessageBoxResult result = MessageBox.Show(Properties.Resources.SettingsWindow_RestoreDefaultConfirm, this.Title,
				MessageBoxButton.YesNo, MessageBoxImage.Question);

			if( result == MessageBoxResult.Yes )
			{
				Settings.DefaultInstance.SaveDefaultSettings();
				KeyMapManager.DefaultInstance.SaveDefaultKeyMaps();

				txtFadeInDuration.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
				txtFadeOutDuration.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
				chkShowPlaybackStatus.GetBindingExpression(CheckBox.IsCheckedProperty).UpdateTarget();

				var xProvider = this.FindResource("KeyMapsDS") as XmlDataProvider;
				xProvider.Refresh();

			}
		}		
		#endregion		
	}
}
